package com.ezlcp.commons.utils;

import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author Weixuan LONG
 * @description: GoogleAuthenticator工具类
 * @date 2022/5/26 9:18
 */
public class GoogleAuthenticator {
    /**
     * 生成的key长度( Generate secret key length)
     */
    public static final int SECRET_SIZE = 10;

    public static final String SEED = "g8GjEvTbW5oVSV7avL47357438reyhreyuryetredLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx";
    /**
     * Java实现随机数算法
     */
    public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";
    /**
     * 最多可偏移的时间 default 3 - max 17
     */
    int window_size = 3;

    /***
     * @description: 设置WindowSize。这是一个整数值，表示我们允许的 30 秒Window的数量。WindowSize越大，我们对时钟偏差的容忍度就越高。
     * @param size WindowSize - 必须 >=1 和 <=17。其他值被忽略
     * @author Weixuan LONG
     * @date 2022/5/26 9:48
     */
    public void setWindowSize(int size) {
        if (size >= 1 && size <= 17) {
            window_size = size;
        }
    }

    /***
     * @description: 生成随机密钥。这必须由服务器保存并与用户帐户相关联，以验证 Google Authenticator 显示的code。用户必须在他们的设备上注册这个密钥。
     * @return java.lang.String  随机密钥
     * @author Weixuan LONG
     * @date 2022/5/26 9:41
     */
    public static String generateSecretKey() {
        SecureRandom sr;
        try {
            sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);
            sr.setSeed(Base64.decodeBase64(SEED));
            byte[] buffer = sr.generateSeed(SECRET_SIZE);
            Base32 codec = new Base32();
            byte[] bEncodedKey = codec.encode(buffer);
            return new String(bEncodedKey);
        } catch (NoSuchAlgorithmException e) {
            // should never occur... configuration error
        }
        return null;
    }

    /***
     * @description: 返回生成并显示 QR 条码的 URL。用户使用智能手机上的 Google Authenticator 应用程序扫描此条形码以注册身份验证码。如果需要，他们还可以手动输入密码
     * @param user 账号
     * @param secret 先前为此用户生成的密钥
     * @return java.lang.String 二维码
     * @author Weixuan LONG
     * @date 2022/5/26 9:42
     */
    public static String getQRBarcodeURL(String user, String secret) {
        String format = "https://chart.googleapis.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth://totp/%s%s?secret=%s";
        return String.format(format, user, "%20Verification%20Code", secret);
    }

    /**
     * 检查用户输入的code是否有效
     *
     * @param secret  密钥
     * @param code    获取到的code
     * @param timeSec 以毫秒为单位的时间（例如 System.currentTimeMillis()）
     * @return boolean
     * @author Weixuan LONG
     * @date 2022/5/26 9:52
     */
    public boolean checkCode(String secret, long code, long timeSec) {
        Base32 codec = new Base32();
        byte[] decodedKey = codec.decode(secret);
        // convert unix msec time into a 30 second "window"
        // this is per the TOTP spec (see the RFC for details)
        long t = (timeSec / 1000L) / 30L;
        // Window is used to check codes generated in the near past.
        // You can use this value to tune how far you're willing to go.
        for (int i = -window_size; i <= window_size; ++i) {
            long hash;
            try {
                hash = verifyCode(decodedKey, t + i);
            } catch (Exception e) {
                // Yes, this is bad form - but
                // the exceptions thrown would be rare and a static
                // configuration problem
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
                // return false;
            }
            if (hash == code) {
                return true;
            }
        }
        // The validation code is invalid.
        return false;
    }

    private static int verifyCode(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
        byte[] data = new byte[8];
        long value = t;
        for (int i = 8; i-- > 0; value >>>= 8) {
            data[i] = (byte) value;
        }
        SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signKey);
        byte[] hash = mac.doFinal(data);
        int offset = hash[20 - 1] & 0xF;
        // We're using a long because Java hasn't got unsigned int.
        long truncatedHash = 0;
        for (int i = 0; i < 4; ++i) {
            truncatedHash <<= 8;
            // We are dealing with signed bytes:
            // we just keep the first byte.
            truncatedHash |= (hash[offset + i] & 0xFF);
        }
        truncatedHash &= 0x7FFFFFFF;
        truncatedHash %= 1000000;
        return (int) truncatedHash;
    }
}